package com.teacher.game.framework.util;

import android.util.Log;
import com.teacher.game.model.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 障碍物管理器 - 统一管理不同类型的障碍物
 * 负责生成、更新、渲染和回收各种障碍物
 */
public class ObstacleManager {
    
    private List<AbstractObstacle> obstacles;
    private BlockPool staticBlockPool;
    
    // 生成概率（根据游戏进度动态调整）
    private float staticBlockChance = 0.6f;    // 60% 静态障碍物
    private float movingBlockChance = 0.25f;   // 25% 移动障碍物  
    private float comboBlockChance = 0.15f;    // 15% 组合障碍物
    
    // 难度控制
    private int currentDifficultyLevel = 1;
    private float gameTimeSeconds = 0;
    
    // 统计信息
    private int totalObstaclesGenerated = 0;
    private int staticCount = 0, movingCount = 0, comboCount = 0;
    
    /**
     * 构造函数
     */
    public ObstacleManager() {
        obstacles = new ArrayList<>();
        staticBlockPool = BlockPool.getInstance();
        
        // 初始化几个静态障碍物
        initializeInitialObstacles();
    }
    
    /**
     * 初始化初始障碍物
     */
    private void initializeInitialObstacles() {
        for (int i = 0; i < 3; i++) {
            StaticBlock block = new StaticBlock(
                i * 250 + 500,  // X坐标
                390,            // Y坐标
                20,             // 宽度
                50              // 高度
            );
            obstacles.add(block);
            staticCount++;
        }
    }
    
    /**
     * 更新所有障碍物
     */
    public void updateAll(float delta, int baseSpeed) {
        gameTimeSeconds += delta;
        updateDifficultyLevel();
        
        // 更新现有障碍物
        for (int i = obstacles.size() - 1; i >= 0; i--) {
            AbstractObstacle obstacle = obstacles.get(i);
            obstacle.update(delta, baseSpeed);
            
            // 移除离开屏幕的障碍物
            if (obstacle.isOffScreen()) {
                obstacles.remove(i);
                recycleObstacle(obstacle);
            }
        }
        
        // 动态生成新障碍物
        generateNewObstacles();
    }
    
    /**
     * 渲染所有障碍物
     */
    public void renderAll(Painter g) {
        for (AbstractObstacle obstacle : obstacles) {
            obstacle.render(g);
        }
        
        // 渲染调试信息
        renderDebugInfo(g);
    }
    
    /**
     * 更新难度等级
     */
    private void updateDifficultyLevel() {
        int newLevel = Math.min(10, (int)(gameTimeSeconds / 30) + 1); // 每30秒提升一级，最高10级
        
        if (newLevel != currentDifficultyLevel) {
            currentDifficultyLevel = newLevel;
            updateDifficultyParameters();
            
            Log.d("ObstacleManager", "难度提升至: " + currentDifficultyLevel + "级");
        }
    }
    
    /**
     * 更新难度参数
     */
    private void updateDifficultyParameters() {
        // 随着难度提升，增加复杂障碍物的概率
        float difficultyFactor = currentDifficultyLevel / 10.0f;
        
        staticBlockChance = Math.max(0.3f, 0.6f - difficultyFactor * 0.3f);
        movingBlockChance = Math.min(0.4f, 0.25f + difficultyFactor * 0.15f);
        comboBlockChance = Math.min(0.3f, 0.15f + difficultyFactor * 0.15f);
        
        // 确保概率总和为1
        float total = staticBlockChance + movingBlockChance + comboBlockChance;
        staticBlockChance /= total;
        movingBlockChance /= total;
        comboBlockChance /= total;
    }
    
    /**
     * 生成新障碍物
     */
    private void generateNewObstacles() {
        // 检查是否需要生成新障碍物
        if (needsNewObstacle()) {
            AbstractObstacle newObstacle = createRandomObstacle();
            if (newObstacle != null) {
                obstacles.add(newObstacle);
                totalObstaclesGenerated++;
            }
        }
    }
    
    /**
     * 检查是否需要新障碍物
     */
    private boolean needsNewObstacle() {
        if (obstacles.isEmpty()) return true;
        
        // 检查最右侧障碍物的位置
        float rightmostX = Float.MIN_VALUE;
        for (AbstractObstacle obstacle : obstacles) {
            rightmostX = Math.max(rightmostX, obstacle.getRightEdge());
        }
        
        // 当最右侧障碍物距离屏幕右边缘小于一定距离时，生成新障碍物
        int screenWidth = 800; // GameMainActivity.GAME_WIDTH
        return rightmostX < screenWidth + 200;
    }
    
    /**
     * 创建随机障碍物
     */
    private AbstractObstacle createRandomObstacle() {
        float random = (float) Math.random();
        float x = 900; // 屏幕右侧外
        float y = 350; // 默认Y坐标
        
        AbstractObstacle newObstacle = null;
        
        if (random < staticBlockChance) {
            // 创建静态障碍物
            newObstacle = new StaticBlock(x, y, 20, 50);
            staticCount++;
            
        } else if (random < staticBlockChance + movingBlockChance) {
            // 创建移动障碍物
            newObstacle = new MovingBlock(x, y, 20, 50);
            movingCount++;
            
        } else {
            // 创建组合障碍物
            newObstacle = new ComboBlock(x, y, 20, 50);
            comboCount++;
        }
        
        // 随机化位置
        if (newObstacle != null) {
            randomizeObstaclePosition(newObstacle);
        }
        
        return newObstacle;
    }
    
    /**
     * 随机化障碍物位置
     */
    private void randomizeObstaclePosition(AbstractObstacle obstacle) {
        float spacing = RandomNumberGenerator.getRandIntBetween(180, 280);
        
        // 找到最右侧障碍物位置
        float rightmostX = 800; // 默认屏幕宽度
        for (AbstractObstacle existing : obstacles) {
            rightmostX = Math.max(rightmostX, existing.getRightEdge());
        }
        
        float newX = rightmostX + spacing;
        float newY = RandomNumberGenerator.getRandIntBetween(250, 390);
        
        obstacle.reset(newX, newY);
    }
    
    /**
     * 回收障碍物
     */
    private void recycleObstacle(AbstractObstacle obstacle) {
        // 这里可以实现对象池回收逻辑
        // 目前简单地让垃圾收集器处理
        
        // 统计信息更新
        switch (obstacle.getType()) {
            case STATIC:
                staticCount--;
                break;
            case MOVING:
                movingCount--;
                break;
            case COMBO:
                comboCount--;
                break;
        }
    }
    
    /**
     * 碰撞检测
     */
    public AbstractObstacle checkCollisions(Player player) {
        for (AbstractObstacle obstacle : obstacles) {
            if (obstacle.isActive() && !obstacle.isPassed()) {
                if (CollisionManager.checkPlayerObstacleCollision(player, obstacle)) {
                    return obstacle;
                }
            }
        }
        return null;
    }
    
    /**
     * 检查玩家是否越过障碍物
     */
    public List<AbstractObstacle> checkPassedObstacles(Player player) {
        List<AbstractObstacle> passed = new ArrayList<>();
        
        for (AbstractObstacle obstacle : obstacles) {
            if (!obstacle.isPassed() && 
                CollisionManager.checkPlayerPassedObstacle(player, obstacle)) {
                obstacle.setPassed(true);
                passed.add(obstacle);
            }
        }
        
        return passed;
    }
    
    /**
     * 渲染调试信息
     */
    private void renderDebugInfo(Painter g) {
        if (DebugHUD.getInstance().isEnabled()) {
            g.setColor(android.graphics.Color.WHITE);
            g.drawString("障碍物统计:", 10, 100);
            g.drawString(String.format("静态:%d 移动:%d 组合:%d", staticCount, movingCount, comboCount), 10, 115);
            g.drawString("难度等级: " + currentDifficultyLevel, 10, 130);
            g.drawString("总生成: " + totalObstaclesGenerated, 10, 145);
        }
    }
    
    /**
     * 重置障碍物管理器
     */
    public void reset() {
        obstacles.clear();
        gameTimeSeconds = 0;
        currentDifficultyLevel = 1;
        totalObstaclesGenerated = 0;
        staticCount = 0;
        movingCount = 0;
        comboCount = 0;
        
        updateDifficultyParameters();
        initializeInitialObstacles();
    }
    
    /**
     * 获取当前障碍物列表（只读）
     */
    public List<AbstractObstacle> getObstacles() {
        return new ArrayList<>(obstacles);
    }
    
    /**
     * 获取障碍物统计信息
     */
    public String getStatistics() {
        return String.format("障碍物统计 - 静态:%d 移动:%d 组合:%d | 难度:%d级 | 总生成:%d", 
                staticCount, movingCount, comboCount, currentDifficultyLevel, totalObstaclesGenerated);
    }
    
    /**
     * 获取当前难度等级
     */
    public int getDifficultyLevel() {
        return currentDifficultyLevel;
    }
    
    /**
     * 强制设置难度等级（用于测试）
     */
    public void setDifficultyLevel(int level) {
        currentDifficultyLevel = Math.max(1, Math.min(10, level));
        updateDifficultyParameters();
    }
}